from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token

from app import LogService
from app.models import Passenger
from presenter import PassengerPresenter
from utils import StateCode, create_response

login_bp = Blueprint('login', __name__)


@login_bp.route('/login', methods=['POST'])
def login():
    data = request.json
    account = data.get('account')
    password = data.get('password')
    if not account or not password:
        return jsonify(create_response(StateCode.PARAMS_ERROR)), 400
    user = Passenger.verifyPassenger(account, password)
    if user:
        access_token = create_access_token(identity=user.id)
        user_presenter = PassengerPresenter(user, {"token": access_token}).as_dict()
        LogService.log()
        return jsonify(create_response(StateCode.SUCCESS, data=user_presenter)), 200
    return jsonify(create_response(StateCode.PASSWORD_INCORRECT)), 400
